// pages/real/homepage/index.js

import Toast from '../../../vant-weapp/dist/toast/toast'
const app = getApp()
const utils = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page:1,
    pageG:1,
    rows:20,
    grows:5,
    filterSort:0,
    compRealFlag:true,
    hotRealFlag:false,
    compGroundFlag:true,
    hotGroundFlag:false,
    compreFlag:true,
    spaceFlag:true,
    hotFlag:false,
    contrFilterFlag:false,
    groundFilterFlag:false,
    browseNum:null,
    contributeTypes:"",
    // tabBarHeight:app.globalData.screenHeight - windowHeight,
    // [{ id: 'dr', property: 'dr', value: '0', operator: '=' }]
    showPopup:false,
    showGroundPopup:false,
    capBarMoveFlag:false,
    topImgUrls:"",
    navTop:wx.getMenuButtonBoundingClientRect().top,
    menuHeight:app.globalData.menuHeight,  
    navHeight: app.globalData.navHeight,
    isIphoneX: app.globalData.isIphoneX,
    topTabVal:1,
    allFilterList:[],
    realContributList:[],
    subFilterList:{},
    subGroundFilterList:{},
    topTabList:[
      {
        id:1,
        name:"客户晒家",
        flag:true
      },
      {
        id:2,
        name:"设计vs实得",
        flag:false
      }
    ],
    copyFilterRealList:{},
    copyFilterGroundList:{},
    filterTypeList:[],
    filterModelList:[],//户型
    filterAreaList:[],//面积
    filterCityList:[],//地区
    filterVideoTypeList:[],
    filterStyleList:[],
    filterSpaceList:[],
    filterCategoryList:[],
    leftList:[],
    rightList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 2
    })
  }
    this.handleGetPageList()
    this.handleGetAllDictList()
  },
  // handleClickLikn(e){
  //   console.log(e)
  //   const {linkAddress, id ,linkType}=e.currentTarget.dataset.link
  //   // if(link){
  //   //    wx.navigateTo({
  //   //     url: link,
  //   //     fail(){
  //   //       wx.switchTab({
  //   //         url: link
  //   //       })
  //   //     }
  //   //   })
  //   // }
  // },
  handleClickLikn(e){
    // const { url , id, type }
    const linkItem = e.currentTarget.dataset.link
    const url=linkItem.linkAddress
    const id=linkItem.id
    const type=linkItem.linkType
    const params = {id: id}

    if(type === 'PICTURE') {
      wx.navigateTo({
        url: `/pages/picShow/index?url=${encodeURIComponent(url)}`,
        success: () => {
          utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
            // 阅览量
          })
        }
      })
    } else {
      //tab页
      if(url === '/pages/home/main/index' || 
        url === '/pages/Featured/main/index' || 
        url==='pages/real/homepage/index' ||
        url==="/pages/afflatus/main/index" || 
        url === '/pages/mine/main/index' || 
        url === '/pages/design/main/index'
      ) {
        wx.switchTab({
          url: url,
          success: () => {
            utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
              // 阅览量
            })
          }
        })
      } else {
        // 非tab页
        const newURl = url.split('?')[0] ? url.split('?')[0] : url
        if(newURl === '/pages/H5/main/index') {
        const kujialeURl = url.split('?url=')[1] ? url.split('?url=')[1] : ''
          wx.navigateTo({
            url: `/pages/H5/main/index?url=${encodeURIComponent(kujialeURl)}`,
            success: () => {
              utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
                // 阅览量
              })
            }
          })
        }
        else {
          wx.navigateTo({
            url: url,
            success: () => {
              utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
                // 阅览量
              })
            }
          })
        }
      }
    }
  },
  handleGetAllDictList(){
    utils.$http(app.globalData.api.getRealIndexPageTopImageUrl, {}, 'GET', false, 'JSON').then(res => {
      if(res.success){
        if(res.data && res.data.length){
          this.setData({
            topImgUrls:res.data
          })
        }
      }
    })
    utils.$http(app.globalData.api.getRealMyGroundAllCitys, {}, 'GET', false, 'JSON').then(res => {
      if(res.success){
        if(res.data && res.data.length){
          this.setData({
            filterCityList:res.data.map((item,index)=>{
              const str={
                code:item,
                name:item,
                id:index,
                flag:false
              }
              return str
            })
          })
        }
      }
    })
    utils.$http(app.globalData.api.getRealMyGroundAllRooms, {}, 'GET', false, 'JSON').then(res => {
      if(res.success){
        if(res.data && res.data.length){
          this.setData({
            filterModelList:res.data.map((item,index)=>{
              item.code=item.value || ''
              item.id=index
              item.flag=false
              return item
            })
          })
        }
      }
    })
    
    utils.$http(app.globalData.api.getRealVeidoAllStyle, {}, 'GET', false, 'JSON').then(res => {
      if(res.success){
       console.log(res)
      const  styles=res.data.map(dd=>{
        dd.flag=false
        dd.name=dd.styleName
        return dd
      })
      this.setData({
        filterStyleList:styles,
      })
      }
    })
    utils.$http(app.globalData.api.getRealContribueAllDict, {}, 'POST', false, 'JSON').then(res => {
      if(res.success){
        let contrList=[]
        let vType=[]
        let areas=[]
          res.data.forEach(item=>{
            if(item.dictTypeCode==='SUBMISSION_TYPE'){
              contrList=item.dictionaryLists.map(dd=>{
                dd.flag=false
                dd.id=dd.dictId
                dd.code=dd.dictCode
                dd.name=dd.dictName
                return dd
              })
            }else if(item.dictTypeCode==='VIDEO_TYPE'){
              vType=item.dictionaryLists.map(dd=>{
                dd.flag=false
                dd.id=dd.dictId
                dd.code=dd.dictCode
                dd.name=dd.dictName
                return dd
              })
            }else if(item.dictTypeCode==='AREA'){
              areas=item.dictionaryLists.map(dd=>{
                dd.flag=false
                dd.id=dd.dictId
                dd.code=dd.dictCode
                dd.name=dd.dictName
                return dd
              }).sort(this.objectSort('dictCode'))
            }
          })
          this.setData({
            filterTypeList:contrList,
            filterVideoTypeList:vType,
            filterAreaList:areas
          })
      }
    })
    utils.$http(app.globalData.api.GetFeaturedAllOnespace, {}, 'Get', false, 'JSON').then(res => {
      if(res.success){
        const list=res.data.map(item=>{
            item.flag=false
            item.name=item.spaceName
            item.code=item.spaceCode 
            return item
          })
        this.setData({
          filterSpaceList:list
        })
        
      }
     })
  },
  objectSort(property) {
    return function (Obj1,Obj2) {
          return Obj1[property]-Obj2[property]
    }
  },
  hendleGetCateInSpace(id){
    const str={
      page:1,
      rows:50,
      spaceId:id
    }
    utils.$http(app.globalData.api.getRealSpaceInCateList, str, 'POST', false, 'JSON').then(res => {
      if(res.success){
        this.setData({
          filterCategoryList:res.data.records.map(item=>{
            item.code=item.categoryCode
            item.name=item.categoryName
            return item
          })
        })
      }
    })
  },
  // selectSpace(options){     
  //   const {item}=option.currentTarget.dataset
  //   const {filterSpaceList}=this.data

  // },
  handleGetRealGroundList(){
    const {pageG,grows,filterSort,subGroundFilterList} =this.data
    const str={
      page:pageG,
      rows:grows,
      ...subGroundFilterList,
      sort:filterSort
    }
    utils.$http(app.globalData.api.getRealActualTemplate, str, 'POST', true, 'JSON').then(res => {
      if(res.success){
        this.setData({
          realContributList:this.data.realContributList.concat(res.data.records) 
        })
      }
    })
    
  },
  indexConditFitler(option){
    const {name,item,list}=option.currentTarget.dataset
    // console.log(name,item,list)
    list.forEach(l=>{
      if(l.id===item.id){
        l.flag=!l.flag
      }else{
        l.flag=false
      }
    })
    if(name==='filterSpaceList'){
      if(![2,3,'2','3'].includes(this.data.contributeTypes)) this.hendleGetCateInSpace(item.id)
    }else if(name==='filterTypeList'){
      this.setData({
        contributeTypes:item.code,
        spaceFlag:true,
      })
      this.handleCleanFilter()
    }else if(name==='filterVideoTypeList'){
      if(item.code==='1'){
        this.setData({
          spaceFlag:false,
          filterSpaceList:this.data.filterSpaceList.map(fil=>{
            fil.flag=false
            return fil
          })
        })
      }else{
        this.setData({
          spaceFlag:true
        })
      }
    }
    this.setData({
      [name]:list
    })
  },
  handleCancelFilter(){
    const { contrFilterFlag , groundFilterFlag , topTabVal,copyFilterGroundList,copyFilterRealList}=this.data 
    if(topTabVal===1){
      if(!contrFilterFlag){
           this.handleCleanFilter()
      }else{
        this.setData({
          filterTypeList:copyFilterRealList.filterTypeList,
          filterVideoTypeList:copyFilterRealList.filterVideoTypeList,
          filterStyleList:copyFilterRealList.filterStyleList,
          filterSpaceList:copyFilterRealList.filterSpaceList,
          filterCategoryList:copyFilterRealList.filterCategoryList,
        })
      }
    }else{
      if(!groundFilterFlag){
        this.handleCleanFilter()
   }else{
    this.setData({
      filterModelList:copyFilterGroundList.filterModelList,
      filterAreaList:copyFilterGroundList.filterAreaList,
      filterStyleList:copyFilterGroundList.filterStyleList,
      filterCityList:copyFilterGroundList.filterCityList,
    })
  }
    }
    this.onClose()
  },
  handleReturnNewArr(list){
    return list.map(item=>{
      item.flag=false
      return item
    })
  },
  handleCleanFilter(){
    const {topTabVal,filterTypeList,filterVideoTypeList,filterStyleList,filterSpaceList,filterModelList,filterCityList,filterAreaList} =this.data 
    if(topTabVal===1){
      this.setData({
        filterTypeList: this.handleReturnNewArr(filterTypeList),
        filterVideoTypeList:this.handleReturnNewArr(filterVideoTypeList),
        filterStyleList:this.handleReturnNewArr(filterStyleList),
        filterSpaceList:this.handleReturnNewArr(filterSpaceList),
        filterCategoryList:[],
        subFilterList:{}
      })
    }else{
      this.setData({
        filterStyleList:this.handleReturnNewArr(filterStyleList),
        filterModelList:this.handleReturnNewArr(filterModelList),
        filterCityList:this.handleReturnNewArr(filterCityList),
        filterAreaList:this.handleReturnNewArr(filterAreaList),
        subGroundFilterList:{}
      })
    }
   
  },
  //深拷贝筛选条件
  handleDeepCopyFilter(list){
    return JSON.parse(JSON.stringify(list))
  },
  getFilterConditToSearch(){
    const {filterTypeList,filterVideoTypeList,filterStyleList,filterSpaceList,filterCategoryList
    ,filterModelList,filterAreaList,filterCityList}=this.data
    if(this.data.topTabVal===1){
    const subFilterLists={}
    let allList=[]
    const cate=[
      {
        name:"品类",
        list:filterCategoryList
      }
    ]
    const noCate=[
      {
        name:"投稿类型",
        list:filterTypeList
      },
      {
        name:"视频类型",
        list:filterVideoTypeList
      },
      {
        name:"风格",
        list:filterStyleList
      },
      {
        name:"空间",
        list:filterSpaceList
      }
    ]
    if(filterCategoryList.length===0){
      allList=noCate
    }else{
      allList=noCate.concat(cate)
    }
    // const canContinue=allList.some(item=>{
    //  return item.list.some(i=>i.flag)
    // })
    // if(!canContinue){
    //   wx.showToast({ icon: 'error', title: '请选择筛选条件', duration: 1000 })
    // }else{
      allList.forEach(item=>{
        item.list.forEach(s=>{
          if(s.flag){
            if(item.name==="投稿类型"){
              subFilterLists.contributeType=s.code || null
            }else if(item.name==="视频类型"){
              subFilterLists.videoType=s.code || null
            }else if(item.name==="风格"){
              subFilterLists.styleCode=s.code || null
              subFilterLists.styleName=s.name || null
            }else if(item.name==="空间"){
              subFilterLists.spaceCode=s.code || null
              subFilterLists.spaceName=s.name || null
            }else if(item.name==="品类"){
              subFilterLists.categoryCode=s.code || null
              subFilterLists.categoryName=s.name || null
            }
          }
        })
      })
      this.onClose()
      const newFilterReal={
        filterCategoryList:this.handleDeepCopyFilter(filterCategoryList),
        filterTypeList:this.handleDeepCopyFilter(filterTypeList),
        filterVideoTypeList:this.handleDeepCopyFilter(filterVideoTypeList),
        filterStyleList:this.handleDeepCopyFilter(filterStyleList),
        filterSpaceList:this.handleDeepCopyFilter(filterSpaceList),
      }
      this.setData({
        subFilterList:subFilterLists || {},
        contrFilterFlag:true,
        copyFilterRealList:newFilterReal
      })
      this.handleInitSearch()
      // this.handleCleanFilter()
    // }
    }else{
      const subGroundFilterLists={}
    const  reals=[
      {
        name:"户型",
        list:filterModelList
      },
      {
        name:"面积",
        list:filterAreaList
      },
      {
        name:"风格",
        list:filterStyleList
      },
      {
        name:"城市",
        list:filterCityList
      }
    ]
    console.log(this.data.filterStyleList)
    reals.forEach(item=>{
      item.list.forEach(s=>{
        if(s.flag){
          if(item.name==="户型"){
            subGroundFilterLists.livingRoom=s.code || ''
          }else if(item.name==="面积"){
            subGroundFilterLists.houseArea=s.name || null
          }else if(item.name==="风格"){
            subGroundFilterLists.styleId=s.id || null
            // subGroundFilterLists.styleName=s.name || null
          }else if(item.name==="城市"){
            subGroundFilterLists.city=s.code || null
          }
        }
      })
    })
    this.onClose()
    const newFilterGround={
      filterStyleList:this.handleDeepCopyFilter(filterStyleList),
      filterModelList:this.handleDeepCopyFilter(filterModelList),
      filterAreaList:this.handleDeepCopyFilter(filterAreaList),
      filterCityList:this.handleDeepCopyFilter(filterCityList),
    }
    this.setData({
      subGroundFilterList:subGroundFilterLists || {},
      groundFilterFlag:true,
      copyFilterGroundList:newFilterGround
    })
    this.handleInitSearch()
    }
    
  },
  handleGetPageList(){
    const {page,rows,browseNum,subFilterList}=this.data
    const list={
      page,
      rows,
      approveState:1,
      upState:0,
      browseNum,
      ...subFilterList
    }
    
    utils.$http(app.globalData.api.getRealVeidoDataList, list, 'POST', true, 'JSON').then(res => {
      // console.log(res)
      const {leftList=[],rightList=[]} =this.data
      if(res.success){
        const data=res.data.records
        if(data.length>0){
          if(data.length===1){
           this.setData({
             leftList:leftList.concat(data)
            //  browseNum:null
           })
          }else{
            // const rights=[]
            // const lefts=[]
            data.forEach((item,index)=>{
              if((index+1)%2===0){
                // rights.push(item)
                rightList.push(item)
              }else{
                // lefts.push(item)
                leftList.push(item)
              }
            })
            
            this.setData({
              rightList,
              leftList
              // browseNum:null
            })
          }
        }
        // res.data.records.for
      }
    })
  },
  //回到顶部
  goTop(){
    if(wx.pageScrollTo){
      wx.pageScrollTo({
        scrollTop: 0,
      })
    }
  },
  handleSwitchTab(list){
    this.goTop()
    const { compRealFlag ,compGroundFlag, hotGroundFlag,hotRealFlag,topTabList,realContributList } =this.data
    const lists=list.currentTarget.dataset.list
    topTabList.forEach(t=>{
      if(t.id===lists.id){
        t.flag=true
      }else{
        t.flag=false
      }
      return t
    })
    this.setData({
      topTabList,
      topTabVal:lists.id
    })
    if(lists.id===1){
      this.setData({
        compreFlag:compRealFlag,
        hotFlag:hotRealFlag,
      })
    }else{ 
      this.setData({
      compreFlag:compGroundFlag,
      hotFlag:hotGroundFlag,
    })
      if(realContributList.length===0){
        this.handlePubConfigSet({isReal:1})
        this.handleGetRealGroundList()
      }
    }
  },
  goWholePage(){
    wx.navigateTo({
      url: '/pages/real/wholevideo/index',
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        // res.eventChannel.emit('casepage', { data })
      }
    })
  },
  handleSearchHot(){
    this.setData({
    compreFlag:false,
    hotFlag:true,
    filterSort:2
  })
  if(this.data.topTabVal===1){
    this.setData({
      compRealFlag:false,
      hotRealFlag:true
    })
    this.handlePubConfigSet({hot:1})
    this.handleGetPageList()
  }else{
    this.setData({
      compGroundFlag:false,
      hotGroundFlag:true
    })
    this.handlePubConfigSet()
    this.handleGetRealGroundList()
  }
  },
  handlePubConfigSet(obj){
    const pageNum=JSON.parse(JSON.stringify(this.data.page))
    const pageGrNum=JSON.parse(JSON.stringify(this.data.pageG))
    const hots={
       browseNum:1
    }
    let initSet={}
    if(this.data.topTabVal===1){
      initSet={
        leftList:[],
        rightList:[],
      }
    }else{
      initSet={
        realContributList:[]
      }
    }
    const str={
      page:1,
      pageG:1,
    }
    if(obj && obj.hot){
       this.setData({
      ...str,
      ...initSet,
      ...hots
    })
    }else if(obj && obj.isReal){
      this.setData({
        pageG:pageGrNum,
        page:pageNum
      })
    }else{
      this.setData({
        ...str,...initSet,browseNum:null
      })
    }
  },
  goMyLive(){
    wx.navigateTo({
      url: '/pages/real/myLive/index',
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        // res.eventChannel.emit('casepage', { data })
      }
    })
  },
  showFilterPage(){
    if(this.data.topTabVal===1){
       this.setData({
      showPopup:true
    })
    }else{
      this.setData({
        showGroundPopup:true
      })
    }
   
  },
  onClose(){
    this.setData({
      showPopup:false,
      showGroundPopup:false
    })
  },
  goVideoPage(){
    wx.navigateTo({
      url: '/pages/real/videoDetails/index',
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        // res.eventChannel.emit('casepage', { data })
      }
    })
  },
  handleInitSearch(){
    this.setData({
      compreFlag:true,
      hotFlag:false,
      filterSort:0
    })
    if(this.data.topTabVal===1){
      this.handlePubConfigSet()
      this.handleGetPageList()
      this.setData({
        compRealFlag:true,
        hotRealFlag:false
      })
    }else{  
      this.setData({
      compGroundFlag:true,
      hotGroundFlag:false
      })
      this.handlePubConfigSet()
      this.handleGetRealGroundList()
    }
  },
  /**
   * 获取本地用户信息
  */
  getLocalUserInfo: function(){
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo){
      this.setData({ userInfo, phone: userInfo.phone })
    }
  },
  toLoginPage(){
    const userInfo = wx.getStorageSync("userInfo")
    const phone = wx.getStorageSync('phone')
    let message = ''
    if(!userInfo) {
      message = '未登陆，是否跳到登陆页登陆'
    }  
    wx.showModal({
      title: '提示',
      content: message,
      success:function(res) {
        if(res.confirm){
          wx.navigateTo({
            url: '/pages/mine/register/index'
          });
        }
      }
    })
  },
  goContriPage(){
    const userInfo = wx.getStorageSync("userInfo")
    const phone = wx.getStorageSync('phone')
    if(!userInfo){
      this.toLoginPage()
    }else{
        wx.navigateTo({
          url: '/pages/real/contribute/index',
          success: function(res) {
            // 通过eventChannel向被打开页面传送数据
            // res.eventChannel.emit('casepage', { data })
          }
    })
    }
  
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.handleInitSearch()
    wx.stopPullDownRefresh()
  },
  //判断页面高度
  onPageScroll(e){
    const isSatisfy = e.scrollTop  >= 280 // 高度大于100的时候 显示白底标签栏
    if(this.data.capBarMoveFlag == isSatisfy) { 
      return false;
    } else {
      this.setData({
        capBarMoveFlag: isSatisfy
      })
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(123)
    const { leftList , rightList , realContributList}=this.data
    if(this.data.topTabVal===1){
      this.data.page=this.data.page+1
      if(leftList.length===0 && rightList.length===0){
        return
      }else{
         this.handleGetPageList()
      }
    }else{
      this.data.pageG=this.data.pageG+1
      if(realContributList.length===0){
        return
      }else{
        this.handleGetRealGroundList()
      }
    }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // const sharerPhone = wx.getStorageSync('phone') || ''
    // const sharerOpenId = wx.getStorageSync('openId') 

    // return {
    //   title: '实景',
    //   imageUrl: utils.filterURL(this.data.topImgUrls[0].bannerImg),
    //   path: "pages/real/homepage/index"  + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId
    // }
    
  }
})